package com.hwd.srb.core.util.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author 黄伟东/Victor
 * @date 2022/1/4 10:34
 * @Description
 */
public class CglibProxyFactory<T> implements MethodInterceptor {
    /** 聚合一个目标对象 */
    private T target;

    /** 通过构造器初始化目标对象 */
    public CglibProxyFactory(T target) {
        this.target = target;
    }

    /** 返回一个目标对象的代理对象 */
    public T getProxyInstance(){
        //1.创建工具类
        Enhancer enhancer = new Enhancer();
        //2.设置父类
        enhancer.setSuperclass(target.getClass());
        //3.设置回调函数
        enhancer.setCallback(this);
        //4.创建子类，即代理对象
        return (T) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib代理被调用了");
        return method.invoke(target,objects);
    }
}
